package com.credit.myapplication

import android.Manifest
import android.os.Bundle
import android.view.MotionEvent
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import com.credit.anypermission.AnyPermission
import com.credit.anypermission.interfaces.RequestInterceptor
import com.credit.anypermission.interfaces.RequestListener

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.text).setOnClickListener {
            AnyPermission.init(this)
                    //可替换其他没有分步的权限请求框架
                    // 参照XPermission里的代码，可自定义实现。
//                .initPermissions(XXPermission())
                .initPermissions(XPermission())
                .permissions(Manifest.permission.CALL_PHONE, Manifest.permission.CAMERA)
                .onBeforeRequest(object : RequestInterceptor<String> {
                    override fun intercept(data: String?, executor: RequestInterceptor.Executor) {
                        showDialog("去授权$data", executor)
                    }
                })
                .onBeenDenied(object : RequestInterceptor<String> {
                    override fun intercept(data: String?, executor: RequestInterceptor.Executor) {
                        showDialog("重新授权$data", executor)
                    }
                })
                .onGoSetting(object : RequestInterceptor<String> {
                    override fun intercept(data: String?, executor: RequestInterceptor.Executor) {
                        showDialog("去设置页设置$data", executor)
                    }
                })
                .request(object : RequestListener {
                    override fun onSuccess() {
                        Toast.makeText(this@MainActivity, "成功", Toast.LENGTH_SHORT).show()
                    }

                    override fun onFailed() {
                        Toast.makeText(this@MainActivity, "失败", Toast.LENGTH_SHORT).show()
                    }
                })
        }
    }

    private fun showDialog(message: String, executor: RequestInterceptor.Executor) {
        AlertDialog.Builder(this)
            .setTitle("授权提醒")
            .setMessage(message)
            .setPositiveButton("授权") { dialog, _ ->
                dialog.dismiss()
                executor.execute()
            }.setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
                executor.cancel()
            }
            .show()
    }
}